﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Minio;
using Minio.DataModel.Args;
using Newtonsoft.Json;

namespace FileUplod.Api.Controllers
{
    [Route("api/[controller][action]")]
    [ApiController]
    public class FileController : ControllerBase
    {
        private readonly IMinioClient _minioClient;
        private string bucketName = "sheepimages";

        public FileController()
        {
            _minioClient = new MinioClient()
                .WithEndpoint("10.223.8.20:9000")
                .WithCredentials("admin", "admin123")
                .WithSSL(false)
                .Build(); 
        }
        /// <summary>
        /// 列出所有桶
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult>ListBuckets()
        {
            //ListBucketsAsync()获取Minio服务器上所有存储桶(bucket)
            var buckets = await _minioClient.ListBucketsAsync().ConfigureAwait(false);
            return Ok(buckets);
        }
        /// <summary>
        /// 上传单个文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UploadFile(IFormFile file)
        {
            var beArgs = new BucketExistsArgs()
                .WithBucket(bucketName);
            bool found = await _minioClient.BucketExistsAsync(beArgs);
            if (!found)
            {
                var mbArgs = new MakeBucketArgs().WithBucket(bucketName);
                await _minioClient.MakeBucketAsync(mbArgs).ConfigureAwait(false);
            }

            var objectName = file.FileName;

            var putArgs = new PutObjectArgs()
                .WithBucket(bucketName)
                .WithObject(objectName)
                .WithStreamData(file.OpenReadStream())
                .WithContentType(file.ContentType)
                .WithObjectSize(file.Length);
            await _minioClient.PutObjectAsync(putArgs).ConfigureAwait(false);


            var getArgs = new PresignedGetObjectArgs()
                .WithBucket(bucketName)
                .WithObject(objectName)
                .WithExpiry(7200);
            var url = await _minioClient.PresignedGetObjectAsync(getArgs).ConfigureAwait(false);
            return Ok(JsonConvert.SerializeObject(url));
        }
    }
}
